package io.renren.controller;


import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.additional.query.impl.QueryChainWrapper;
import io.renren.common.utils.R;
import io.renren.config.*;
import io.renren.entity.*;
import io.renren.service.*;
import io.renren.utils.wxpay.ConfigUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.gavaghan.geodesy.Ellipsoid;

import java.math.BigDecimal;
import java.text.DecimalFormat;


import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import com.sun.jna.ptr.IntByReference;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;




/**
 * 我的界面
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/api")
public class MyMineController {
	private static final String APP_ID = ConfigUtil.getProperty("wx.appid");

	private static final String APP_SECRET = ConfigUtil.getProperty("wx.appsecret");

	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	@Autowired
	UsersService usersService;

	@Autowired
	MerchantService merchantService;

	@Autowired
	TransationdetailService transationdetailService;

	@Autowired
	ShopOrderService shopOrderService;

	@Autowired
	CouponUserService couponUserService;

	@Autowired
	LineQcodeService lineQcodeService;

	@Autowired
	LinePasswordService linePasswordService;

	@Autowired
	RechargeinstructService rechargeinstructService;

	@Autowired
	CustomserviceService customserviceService;

	@Autowired
	IndeximgService indeximgService;

	@Autowired
	ChargedetailinstrustService chargedetailinstrustService;

	@Autowired
	ChargestandardService chargestandardService;



	/**
	 * 用户登陆
	 * @param code
	 * @param headimgurl 用户头像
	 * @param nickname 用户昵称
	 * @param gender 性别
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public R login(@RequestParam("code")String code, @RequestParam("headimgurl")String headimgurl, @RequestParam("nickname")String nickname,
				   @RequestParam("gender")String gender) {
		if(code ==null){
			return R.error("code不能为空");
		}else if(headimgurl ==null){
			return R.error("用户头像不能为空");
		}else if(nickname ==null){
			return R.error("用户昵称不能为空");
		}else{
			String urlopenid = "https://api.weixin.qq.com/sns/jscode2session?appid="+APP_ID+"&secret="+APP_SECRET+"&js_code="+code+"&grant_type=authorization_code";
			JSONObject json = HttpClientUtils.httpRequest(urlopenid,"GET",null);
			String openid = json.getString("openid");
			UsersVOEntity users = usersService.getUserInfoByOpenid(openid);

			if(users!=null){
				users.setLastlogintime(new Date());
				users.setHeadimg(headimgurl);
				users.setUsername(nickname);
				users.setGender(gender);
				users.setLastlogintime(new Date());
				usersService.updateById(users);
			}else{
				users = new UsersVOEntity();
				users.setCreatetime(new Date());
				users.setLastlogintime(new Date());
				users.setOpenid(openid);
				users.setHeadimg(headimgurl);
				users.setUsername(nickname);
				users.setGender(gender);
				usersService.save(users);
			}
			return R.ok().put("userid",users.getId()).put("openid",openid);
		}

	}

	/**
	 * 获取session_key
	 * @param userid
	 * @param code
	 * @return
	 */
	@RequestMapping("/getSessionKey")
	@ResponseBody
	public R getSessionKey(@RequestParam("userid")Integer userid,@RequestParam("code")String code) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else if(code ==null){
			return R.error("code不能为空");
		}else{
			UsersVOEntity user = usersService.getById(userid);
			if(user!=null){
				String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+APP_ID+"&secret="+APP_SECRET+"&js_code="+code+"&grant_type=authorization_code";
				JSONObject jsonObject = HttpClientUtils.httpRequest(url,"GET",null);
				String session_key = jsonObject.getString("session_key");
				return R.ok().put("session_key",session_key).put("openid",user.getOpenid());
			}else{
				return R.error("找不到该用户信息");
			}


		}

	}

	/**
	 * 支付宝用户登陆
	 * @param authCode
	 * @return
	 */
	@RequestMapping("/alipayLogin")
	@ResponseBody
	public R alipayLogin(@RequestParam("authCode")String authCode,@RequestParam("headimg")String headimg,@RequestParam("username")String username) {
		String appId = AlipayConfig.app_id;
		String privateKey = AlipayConfig.merchant_private_key;
		String alipayPublicKey = AlipayConfig.alipay_public_key;
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, appId, privateKey, "json", AlipayConfig.charset, alipayPublicKey, AlipayConfig.sign_type);
		AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
		request.setGrantType("authorization_code");
		request.setCode(authCode);

		try{
			AlipaySystemOauthTokenResponse response = alipayClient.execute(request);
			if (response.isSuccess()) {
				System.out.println("调用成功");
				System.out.println("支付宝用户唯一id：" + response.getUserId());
				System.out.println("token令牌:" + response.getAccessToken());   //访问令牌。通过该令牌调用需要授权类接口

				//支付宝唯一用户ID
				String userId = response.getUserId();

				UsersVOEntity users = usersService.getUserInfoByOpenid(userId);

				if(users!=null){
					users.setLastlogintime(new Date());
					users.setHeadimg(headimg);
					users.setUsername(username);
					users.setLastlogintime(new Date());
					usersService.updateById(users);
				}else{
					users = new UsersVOEntity();
					users.setCreatetime(new Date());
					users.setLastlogintime(new Date());
					users.setOpenid(userId);
					users.setHeadimg(headimg);
					users.setUsername(username);
					users.setGender("男");
					users.setType(1);
					usersService.save(users);
				}
				return R.ok().put("userid",users.getId()).put("openid",userId);

			} else {
				return R.error("调用失败");
			}
		}catch(AlipayApiException e){
			e.printStackTrace();
			return R.error("调用失败");
		}

	}

	/**
	 * 用户信息
	 * @param userid
	 * @return
	 */
	@RequestMapping("/user")
	@ResponseBody
	public R user(@RequestParam("userid")Integer userid) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else{
			UsersVOEntity user = usersService.getById(userid);
			if(user!=null){
				return R.ok().put("headimg",user.getHeadimg())
						.put("username",user.getUsername()).put("id",user.getId())
						.put("telphone",user.getTelphone());
			}else{
				return R.error("找不到该用户");
			}

		}

	}

	/**
	 * 更换手机号
	 * @param userid
	 * @return
	 */
	@RequestMapping("/changeTelphone")
	@ResponseBody
	public R changeTelphone(@RequestParam("userid")Integer userid,@RequestParam("telphone")String telphone) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else if(telphone == null){
			return R.error("要更换的手机号不能为空");
		}else{
			UsersVOEntity user = usersService.getById(userid);
			if(user!=null){
				user.setTelphone(telphone);
				boolean flag = usersService.updateById(user);
				if(flag){
					return R.ok("更换成功");
				}else{
					return R.error("更换失败");
				}
			}else{
				return R.error("找不到该用户");
			}

		}

	}

	/**
	 * 首页获取附近设备
	 * @return
	 */
	@RequestMapping("/device")
	@ResponseBody
	public R device() {

			/*double lon = Double.parseDouble(longitude);
			double lat = Double.parseDouble(latitude);
			//先计算查询点的经纬度范围
			double r = 6371;//地球半径千米
			double dis = 0.5;//0.5千米距离
			double dlng =  2*Math.asin(Math.sin(dis/(2*r))/Math.cos(lat*Math.PI/180));
			dlng = dlng*180/Math.PI;//角度转为弧度
			double dlat = dis/r;
			dlat = dlat*180/Math.PI;
			double minlat =lat-dlat;
			double maxlat = lat+dlat;
			double minlng = lon -dlng;
			double maxlng = lon + dlng;*/
			JSONArray array = new JSONArray();
			List<MerchantEntity> list = merchantService.getNearDevice();
			for(MerchantEntity entity:list){
				JSONObject json = new JSONObject();
				json.put("id",entity.getId());
				json.put("name",entity.getName());
				json.put("longitude",entity.getLongitude());
				json.put("latitude",entity.getLatitude());
				array.add(json);
			}
			return R.ok().put("data",array);



	}


	/**
	 * 获取附近门店
	 * @return
	 */
	@RequestMapping("/nearShop")
	@ResponseBody
	public R nearShop() {

			/*double lon = Double.parseDouble(longitude);
			double lat = Double.parseDouble(latitude);
			//先计算查询点的经纬度范围
			double r = 6371229;//地球半径千米
			double dis = 2;//1千米距离
			double dlng =  2*Math.asin(Math.sin(dis/(2*r))/Math.cos(lat*Math.PI/180));
			dlng = dlng*180/Math.PI;//角度转为弧度
			double dlat = dis/r;
			dlat = dlat*180/Math.PI;
			double minlat =lat-dlat;
			double maxlat = lat+dlat;
			double minlng = lon -dlng;
			double maxlng = lon + dlng;*/
			JSONArray array = new JSONArray();
			List<MerchantEntity> list = merchantService.getNearDevice();
			for(MerchantEntity entity:list){
				JSONObject json = new JSONObject();
				json.put("id",entity.getId());
				json.put("shopname",entity.getName());
				json.put("shoplogo",entity.getShopImg()!=null?entity.getShopImg():"");
				String address = entity.getAddress()!=null?entity.getAddress():"";
				json.put("address",entity.getCity()+entity.getDistrict()+address);
				json.put("longitude",entity.getLongitude());
				json.put("latitude",entity.getLatitude());

				/**
				 * 计算两个坐标之间的距离
				 */

				/*GlobalCoordinates source = new GlobalCoordinates(lat, lon);
				GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(entity.getLatitude()), Double.parseDouble(entity.getLongitude()));

				double meter1 = Utils.getDistanceMeter(target, source, Ellipsoid.Sphere);
				DecimalFormat df = new DecimalFormat("#");
				meter1 = Double.parseDouble(df.format(meter1));
				json.put("distance",meter1);*/
				array.add(json);
			}
			return R.ok().put("data",array);



	}



	/**
	 * 我的钱包
	 * @param userid
	 * @return
	 */
	@RequestMapping("/mywallet")
	@ResponseBody
	public R mywallet(@RequestParam("userid")Integer userid) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else{
			UsersVOEntity user = usersService.getById(userid);
			if(user!=null){
				JSONArray array = new JSONArray();
				List<TransationdetailEntity> list = transationdetailService.getTransationdetail(userid);
				for(TransationdetailEntity entity:list){
					JSONObject json = new JSONObject();
					json.put("name",entity.getName());
					json.put("time",sdf.format(entity.getTime()));
					json.put("money",entity.getMoney());
					array.add(json);
				}
				return R.ok().put("balance",user.getBalance()!=null?user.getBalance():0).put("detail",array);
			}else{
				return R.error("找不到该用户");
			}

		}

	}

	/**
	 * 我的订单
	 * @param userid
	 * @return
	 */
	@RequestMapping("/myorder")
	@ResponseBody
	public R myorder(@RequestParam("userid")Integer userid) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else{
			UsersVOEntity user = usersService.getById(userid);
			if(user!=null){
				JSONArray array = new JSONArray();
				List<ShopOrderEntity> list = shopOrderService.getMyOrder(userid);
				for(ShopOrderEntity entity:list){
					JSONObject json = new JSONObject();
					//MerchantEntity merchantEntity = merchantService.getById(entity.getMerchantid());
					json.put("id",entity.getId());
					json.put("orderno",entity.getOrderSn());
					json.put("ordertime",sdf.format(entity.getAddTime()));
					json.put("merchantname","");
					json.put("useduration",entity.getUseduration());
					json.put("fee",entity.getActualAmount());
					String statu = "";
					if(entity.getOrderStatus()==0){
						statu = "租借中";
					}else if(entity.getOrderStatus()==1){
						statu = "已完成";
					}else if(entity.getOrderStatus()==2){
						statu = "已撤销";
					}else if(entity.getOrderStatus()==3){
						statu = "订单超时";
					}else if(entity.getOrderStatus()==4){
						statu = "申请结束";
					}else if(entity.getOrderStatus()==5){
						statu = "丢失充电宝";
					}
					json.put("statu",statu);
					array.add(json);
				}
				return R.ok().put("order",array);
			}else{
				return R.error("找不到该用户");
			}

		}

	}

	/**
	 * 删除订单
	 * @param orderid
	 * @return
	 */
	@RequestMapping("/deleteOrder")
	@ResponseBody
	public R deleteOrder(@RequestParam("orderid")Integer orderid) {
		if(orderid ==null){
			return R.error("订单id不能为空");
		}else{
			ShopOrderEntity order = shopOrderService.getById(orderid);
			if(order!=null){
				boolean flag = shopOrderService.removeById(orderid);
				if(flag){
					return R.ok("删除成功");
				}else{
					return R.error("删除失败");
				}
			}else{
				return R.error("找不到该订单");
			}

		}

	}

	/**
	 * 我的订单详情
	 * @param orderid
	 * @return
	 */
	@RequestMapping("/myorderdetail")
	@ResponseBody
	public R myorderdetail(@RequestParam("orderid")Integer orderid) {
		if(orderid ==null){
			return R.error("订单id不能为空");
		}else{
			ShopOrderEntity order = shopOrderService.getById(orderid);
			String statu = "";
			if(order!=null){
				if(order.getOrderStatus()==0){
					statu = "租借中";
				}else if(order.getOrderStatus()==1){
					statu = "已完成";
				}else if(order.getOrderStatus()==2){
					statu = "已撤销";
				}else if(order.getOrderStatus()==3){
					statu = "订单超时";
				}else if(order.getOrderStatus()==4){
					statu = "申请结束";
				}else if(order.getOrderStatus()==5){
					statu = "丢失充电宝";
				}
				LineQcodeEntity entity = lineQcodeService.getCodeByDeviceSn(order.getDevicceSn());
				return R.ok().put("devicesn",entity.getQcode()).put("statu",statu).put("useduration",order.getUseduration())
						.put("ordertime",sdf.format(order.getAddTime())).put("endtime",sdf.format(order.getEndtime())).put("orderamount",order.getOrderAmount())
						.put("fee",order.getActualAmount()).put("standard",order.getChargingStandard()).put("ordersn",order.getOrderSn()).put("code",entity.getQcode());
			}else{
				return R.error("找不到该订单");
			}

		}

	}

	/**
	 * 附近门店详情
	 * @param shopid
	 * @return
	 */
	@RequestMapping("/shopdetail")
	@ResponseBody
	public R shopdetail(@RequestParam("shopid")Integer shopid,@RequestParam("longitude")String longitude,@RequestParam("latitude")String latitude) {
		if(shopid ==null){
			return R.error("门店id不能为空");
		}else{
			MerchantEntity merchantEntity = merchantService.getById(shopid);

			if(merchantEntity!=null){
				double lon = Double.parseDouble(longitude);
				double lat = Double.parseDouble(latitude);

				String address = merchantEntity.getAddress()!=null?merchantEntity.getAddress():"";

				/**
				 * 计算两个坐标之间的距离
				 */

				GlobalCoordinates source = new GlobalCoordinates(lat, lon);
				GlobalCoordinates target = new GlobalCoordinates(Double.parseDouble(merchantEntity.getLatitude()), Double.parseDouble(merchantEntity.getLongitude()));

				double meter1 = Utils.getDistanceMeter(target, source, Ellipsoid.Sphere);
				DecimalFormat df = new DecimalFormat("#");
				meter1 = Double.parseDouble(df.format(meter1));
				return R.ok().put("shopimg",merchantEntity.getShopImg()).put("shopname",merchantEntity.getName())
						.put("address",merchantEntity.getCity()+merchantEntity.getDistrict()+address)
						.put("time",merchantEntity.getStartTime()+"-"+merchantEntity.getEndTime())
						.put("distance",meter1).put("longitude",merchantEntity.getLongitude()).put("latitude",merchantEntity.getLatitude());
			}else{
				return R.error("找不到该门店");
			}

		}

	}

	/**
	 * 扫码充电 .put("id",merchantEntity.getId())
	 * @param code
	 * @return
	 */
	@RequestMapping("/codeCharge")
	@ResponseBody
	public R codeCharge(@RequestParam("code")String code) {
		if(code ==null){
			return R.error("二维码编号不能为空");
		}else{
			List<ChargestandardEntity> list = chargestandardService.list(new QueryWrapper<ChargestandardEntity>());
			List<ChargedetailinstrustEntity> lists = chargedetailinstrustService.getChargeinstruct();
			String remark = "";
			if(lists!=null && lists.size()>0){
				remark = lists.get(0).getRemark();

			}
			if(list!=null && list.size()>0){
				JSONArray array = new JSONArray();
				for(ChargestandardEntity entity:list){
					JSONObject one = new JSONObject();
					one.put("time",entity.getTimename());
					one.put("fee",entity.getTimemoney());
					array.add(one);
				}

				return R.ok().put("data",array).put("instruct",remark);
			}else{
				return R.error("找不到该二维码");
			}

		}

	}

	/**
	 * 使用说明详情
	 * @return
	 */
	@RequestMapping("/instructDetail")
	@ResponseBody
	public R instructDetail() {

		List<ChargedetailinstrustEntity> lists = chargedetailinstrustService.getChargeinstruct();
		String instruct = "";
		if(lists!=null && lists.size()>0){
			instruct = lists.get(0).getInstruct();

		}

		return R.ok().put("instructDetail",instruct);



	}

	/**
	 * 我的优惠券
	 * @param userid
	 * @return
	 */
	@RequestMapping("/mycoupon")
	@ResponseBody
	public R mycoupon(@RequestParam("userid")Integer userid) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else{
			JSONArray array = new JSONArray();
			List<CouponUserVOEntity> list = couponUserService.getCouponByUserId(userid);
			for(CouponUserVOEntity entity:list){
				JSONObject json = new JSONObject();
				json.put("id",entity.getId());
				json.put("name",entity.getCouponname());
				json.put("denomination",entity.getDenomination());
				json.put("statu",entity.getStatu());
				array.add(json);
			}
			return R.ok().put("coupon",array);

		}

	}

	/**
	 * 支付下单
	 * @param userid 用户id
	 * @param time  充电时长
	 * @param money 支付金额
	 * @param code  二维码编号
	 * @return
	 */
	@RequestMapping("/orderPay")
	@ResponseBody
	public R orderPay(@RequestParam("userid")Integer userid,@RequestParam("time")String time,
				   @RequestParam("money")String money,@RequestParam("code")String code) {

		if(userid ==null){
			return R.error("用户id不能为空");
		}else if(time == null){
			return R.error("充电时长不能为空");
		}else if(money == null){
			return R.error("支付金额不能为空");
		}else if(code == null){
			return R.error("二维码编号不能为空");
		}else{
			LineQcodeEntity lineQcodeEntity = lineQcodeService.getCodeByCodeSn(code);

			if(lineQcodeEntity!=null){
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				String ordersn = "XD"+format.format(new Date());
				PayController payController=new PayController();
				UsersVOEntity user = usersService.getById(userid);

				LineQcodeEntity entity = lineQcodeService.getCodeByCodeSn(code);
				/**
				 * 添加订单信息
				 */
				ShopOrderEntity orderEntity = new ShopOrderEntity();
				orderEntity.setActualAmount(money);
				orderEntity.setAddTime(new Date());
				orderEntity.setChargingStandard(time+"h/"+money+"元");

				orderEntity.setOrderSn(ordersn);
				orderEntity.setOrderStatus(2);
				orderEntity.setPayType(0);
				orderEntity.setPayStatus(1);
				orderEntity.setOrderAmount(money);
				orderEntity.setUseduration(time);
				orderEntity.setUserId(userid);

				LinePasswordEntity passwordEntity = linePasswordService.getByQCodeId(entity.getId());
				orderEntity.setDevicceSn(passwordEntity.getDevicesn());

				//截止时间
				long currentTime = System.currentTimeMillis() + Integer.parseInt(time)*60 * 60 * 1000;
				Date date = new Date(currentTime);
				orderEntity.setEndtime(date);

				//MerchantEntity merchantEntity = linePasswordService.getChargeStandard(entity.getId());
				orderEntity.setDevicceSn(passwordEntity.getDevicesn());

				shopOrderService.save(orderEntity);

				/**
				 * 添加消费记录
				 */
				TransationdetailEntity transationdetailEntity = new TransationdetailEntity();
				transationdetailEntity.setUserid(userid);
				transationdetailEntity.setMoney(money);
				transationdetailEntity.setName("充电费用");
				transationdetailEntity.setTime(new Date());
				transationdetailEntity.setStatu(1);
				transationdetailEntity.setSn(ordersn);
				transationdetailService.save(transationdetailEntity);

				return payController.orderPay(new BigDecimal(money),user.getOpenid(),time,userid,lineQcodeEntity.getId(),ordersn);

			}else{
				return R.error("找不到该二维码");
			}

		}

	}

	/**
	 * 充电详情
	 * @param ordersn 订单编号
	 * @param code 二维码编号
	 * @return
	 */
	@RequestMapping("/chargeDetail")
	@ResponseBody
	public R chargeDetail(@RequestParam("ordersn")String ordersn,@RequestParam("code")String code) {
		if(ordersn ==null){
			return R.error("订单编号不能为空");
		}else if(code == null){
			return R.error("二维码编号不能为空");
		}else{
			ShopOrderVOEntity entity = shopOrderService.getOrderByOrderSn(ordersn);
			if(entity!=null){
				long diff = entity.getRestime().getTime() - new Date().getTime();//这样得到的差值是毫秒级别

				LineQcodeEntity lineQcodeEntity = lineQcodeService.getCodeByCodeSn(code);
				String passwrod = "";
				if(StringUtils.isBlank(entity.getPassword())){
					IntByReference cnt = new IntByReference(lineQcodeEntity.getCnt());//
					byte[] pass = new byte[6];
					Zdmmxencrypt.Clibrary.INSTANTCE.zdmmxencrypt(cnt, 2718793814L,Integer.parseInt(lineQcodeEntity.getSn()), Integer.parseInt(entity.getUseduration()), pass);

					for (int i = 0; i < pass.length; i++) {
						passwrod += pass[i];
					}
					LinePasswordEntity linePasswordEntity = linePasswordService.getByQCodeId(lineQcodeEntity.getId());
					linePasswordEntity.setPassword(passwrod);
					linePasswordService.saveOrUpdate(linePasswordEntity);
				}else{
					passwrod = entity.getPassword();
				}


				//跟新流水号
				lineQcodeEntity.setCnt(lineQcodeEntity.getCnt()+1);
				lineQcodeService.saveOrUpdate(lineQcodeEntity);

				return R.ok().put("password",passwrod).put("restime",diff)
						.put("qcode",entity.getQcode());
			}else{
				return R.error("找不到该订单信息");
			}

		}

	}


	/**
	 * 我的充值(微信)
	 * @param userid 用户id
	 * @param money 充值金额
	 * @return
	 */
	@RequestMapping("/recharge")
	@ResponseBody
	public R recharge(@RequestParam("userid")Integer userid,@RequestParam("money")String money) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else if(money ==null){
			return R.error("充值金额不能为空");
		}else{
			PayController payController=new PayController();
			UsersVOEntity user = usersService.getById(userid);
			return payController.ourRecharge(new BigDecimal(money),userid,user.getOpenid());
		}

	}

	/**
	 * 我的充值(支付宝)
	 * @param userid 用户id
	 * @param money 充值金额
	 * @return
	 */
	@RequestMapping("/alipayRecharge")
	@ResponseBody
	public R alipayRecharge(@RequestParam("userid")Integer userid,@RequestParam("money")String money) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else if(money ==null){
			return R.error("充值金额不能为空");
		}else{
			PayController payController=new PayController();
			UsersVOEntity user = usersService.getById(userid);
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String ordersn = "XD"+format.format(new Date());
			return payController.alipayCashSign(ordersn,money,"充值消费","",user.getOpenid());
		}

	}

	/**
	 * 充值说明
	 * @return
	 */
	@RequestMapping("/rechargeInstruct")
	@ResponseBody
	public R rechargeInstruct() {
		List<RechargeinstructEntity> list = rechargeinstructService.getRechargeinstruct();
		if(list!=null && list.size()>0){
			RechargeinstructEntity entity = list.get(0);
			return R.ok().put("instrust",entity.getInstruct());
		}else{
			return R.error("暂无数据");
		}

	}

	/**
	 * 客服
	 * @return
	 */
	@RequestMapping("/customService")
	@ResponseBody
	public R customService() {
		List<CustomserviceEntity> list = customserviceService.getServiceTelphone();
		if(list!=null && list.size()>0){
			CustomserviceEntity entity = list.get(0);
			return R.ok().put("telphone",entity.getTelphone());
		}else{
			return R.error("暂无数据");
		}

	}

	/**
	 * 订单支付成功业务处理
	 * @param ordersn 订单编号
	 */
	@RequestMapping("/orderPayNotify")
	@ResponseBody
	public R orderPayNotify(@RequestParam("ordersn")String ordersn) {

		if(ordersn == null){
			return R.error("订单编号不能为空");
		}else{
			ShopOrderEntity shopOrderEntity = shopOrderService.getShopOrderByOrderSn(ordersn);
			if(shopOrderEntity!=null){
				//支付成功后修改订单状态为租赁中
				shopOrderEntity.setOrderStatus(0);
				shopOrderService.saveOrUpdate(shopOrderEntity);

				//支付成功后修改消费记录为成功
				TransationdetailEntity transationdetailEntity = transationdetailService.getTransationBySn(ordersn);
				if(transationdetailEntity !=null){
					transationdetailEntity.setStatu(0);
					transationdetailService.saveOrUpdate(transationdetailEntity);
				}
				return R.ok();
			}else{
				return R.error("找不到该订单");
			}

		}
	}


	/**
	 * 充值回调
	 *
	 * @param money  充值金额
	 * @param userid 用户id
	 */
	@RequestMapping("/rechargeNotify")
	@ResponseBody
	public R rechargeNotify(@RequestParam("money")String money,@RequestParam("userid")String userid) {
		if(money == null){
			return R.error("充值金额不能为空");
		}else if(userid == null){
			return R.error("用户id不能为空");
		}else{
			/**
			 * 修改用户余额，增加充值金额
			 */
			UsersVOEntity usersVOEntity = usersService.getById(userid);
			usersVOEntity.setBalance(Double.valueOf(usersVOEntity.getBalance())+Double.valueOf(money)+"");
			usersService.updateById(usersVOEntity);

			/**
			 * 添加消费记录
			 */
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			String ordersn = "CZ"+format.format(new Date());
			TransationdetailEntity entity = new TransationdetailEntity();
			entity.setUserid(Integer.parseInt(userid));
			entity.setMoney(money);
			entity.setName("用户充值");
			entity.setTime(new Date());
			entity.setStatu(0);
			entity.setSn(ordersn);
			transationdetailService.save(entity);
			return R.ok();
		}
	}


	/**
	 * 结束订单
	 *
	 * @param ordersn  订单编号
	 */
	@RequestMapping("/closeOrder")
	@ResponseBody
	public R closeOrder(@RequestParam("ordersn")String ordersn) {
		if(ordersn == null){
			return R.error("订单编号不能为空");
		}else{
			ShopOrderEntity shopOrderEntity = shopOrderService.getShopOrderByOrderSn(ordersn);
			if(shopOrderEntity!=null){
				shopOrderEntity.setOrderStatus(1);
				shopOrderService.saveOrUpdate(shopOrderEntity);

				//订单结束后密码置空
				ShopOrderVOEntity entity = shopOrderService.getOrderByOrderSn(ordersn);
				if(entity !=null){
					LineQcodeEntity lineQcodeEntity = lineQcodeService.getCodeByCodeSn(entity.getQcode());
					if(lineQcodeEntity !=null){
						LinePasswordEntity linePasswordEntity = linePasswordService.getByQCodeId(lineQcodeEntity.getId());
						linePasswordEntity.setPassword("");
						linePasswordService.saveOrUpdate(linePasswordEntity);
					}
				}

				return R.ok();
			}else{
				return R.error("找不到该订单");
			}
		}
	}

	/**
	 * 首页图片
	 * @return
	 */
	@RequestMapping("/indexImg")
	@ResponseBody
	public R indexImg() {
		List<IndeximgEntity> list = indeximgService.getIndeximg();
		if(list!=null && list.size()>0){
			IndeximgEntity entity = list.get(0);
			return R.ok().put("img",entity.getImg()).put("hrefurl",entity.getHrefurl());
		}else{
			return R.error("暂无数据");
		}

	}

	/**
	 * 充电详情使用说明
	 * @return
	 */
	@RequestMapping("/chargeDetailInstruct")
	@ResponseBody
	public R chargeDetailInstruct() {
		List<ChargedetailinstrustEntity> list = chargedetailinstrustService.getChargeinstruct();
		if(list!=null && list.size()>0){
			ChargedetailinstrustEntity entity = list.get(0);
			return R.ok().put("instrust",entity.getInstruct());
		}else{
			return R.error("暂无数据");
		}

	}

	/**
	 * 支付宝支付
	 * @param userid 用户id
	 * @param time  充电时长
	 * @param money 支付金额
	 * @param code  二维码编号
	 * @return
	 */
	@RequestMapping("/alipay")
	@ResponseBody
	public R alipay(@RequestParam("userid")Integer userid,@RequestParam("time")String time,
					@RequestParam("money")String money,@RequestParam("code")String code) {
		if(userid ==null){
			return R.error("用户id不能为空");
		}else if(time == null){
			return R.error("充电时长不能为空");
		}else if(money == null){
			return R.error("支付金额不能为空");
		}else if(code == null){
			return R.error("二维码编号不能为空");
		}else{
			LineQcodeEntity lineQcodeEntity = lineQcodeService.getCodeByCodeSn(code);

			if(lineQcodeEntity!=null){
				SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
				String ordersn = "XD"+format.format(new Date());
				PayController payController=new PayController();
				UsersVOEntity user = usersService.getById(userid);

				LineQcodeEntity entity = lineQcodeService.getCodeByCodeSn(code);
				/**
				 * 添加订单信息
				 */
				ShopOrderEntity orderEntity = new ShopOrderEntity();
				orderEntity.setActualAmount(money);
				orderEntity.setAddTime(new Date());
				orderEntity.setChargingStandard(time+"h/"+money+"元");

				orderEntity.setOrderSn(ordersn);
				orderEntity.setOrderStatus(2);
				orderEntity.setPayType(1);
				orderEntity.setPayStatus(1);
				orderEntity.setOrderAmount(money);
				orderEntity.setUseduration(time);
				orderEntity.setUserId(userid);

				LinePasswordEntity passwordEntity = linePasswordService.getByQCodeId(entity.getId());
				orderEntity.setDevicceSn(passwordEntity.getDevicesn());

				//截止时间
				long currentTime = System.currentTimeMillis() + Integer.parseInt(time)*60 * 60 * 1000;
				Date date = new Date(currentTime);
				orderEntity.setEndtime(date);

				//MerchantEntity merchantEntity = linePasswordService.getChargeStandard(entity.getId());
				orderEntity.setDevicceSn(passwordEntity.getDevicesn());

				shopOrderService.save(orderEntity);

				/**
				 * 添加消费记录
				 */
				TransationdetailEntity transationdetailEntity = new TransationdetailEntity();
				transationdetailEntity.setUserid(userid);
				transationdetailEntity.setMoney(money);
				transationdetailEntity.setName("充电费用");
				transationdetailEntity.setTime(new Date());
				transationdetailEntity.setStatu(1);
				transationdetailEntity.setSn(ordersn);
				transationdetailService.save(transationdetailEntity);

				return payController.alipaySign(ordersn,money,"充电支付","",user.getOpenid());

			}else{
				return R.error("找不到该二维码");
			}

		}

	}

	/**
	 * 获取手机号
	 * @param session_key
	 * @param encryptedData
	 * @param iv
	 * @return
	 */
	@RequestMapping("/getTelphone")
	@ResponseBody
	public R getTelphone(@RequestParam("session_key")String session_key,@RequestParam("encryptedData")String encryptedData
			, @RequestParam("iv")String iv) {

		if(session_key ==null){
			return R.error("session_key不能为空");
		}else if(encryptedData == null){
			return R.error("encryptedData不能为空");
		}else if(iv == null){
			return R.error("iv不能为空");
		}else{
			WXBizDataCrypt wxBizDataCrypt = new WXBizDataCrypt(APP_ID,session_key);
			try{
				JSONObject jsonObject = wxBizDataCrypt.decryptData(encryptedData,iv);
				String telphone = jsonObject.getString("purePhoneNumber");
				return R.ok().put("telphone",telphone);
			}catch (Exception e){
				e.printStackTrace();
				return null;
			}

		}
	}
}
